package com.nbsaas.boot.app.ext.resource;

import com.nbsaas.boot.app.api.apis.AppApi;
import com.nbsaas.boot.app.api.domain.field.AppField;
import com.nbsaas.boot.app.api.domain.request.AppRequest;
import com.nbsaas.boot.app.api.domain.response.AppResponse;
import com.nbsaas.boot.app.ext.apis.AppExtApi;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ResponseObject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class AppExtResource implements AppExtApi {

    @Resource
    private AppApi appApi;

    @Override
    public ResponseObject<AppResponse> create(AppRequest request) {
        ResponseObject<AppResponse> result = new ResponseObject<>();
        if (!StringUtils.hasText(request.getAppKey())) {
            result.setCode(501);
            result.setMsg("应用标识不能为空");
            return result;
        }

        Long num = appApi.countData(Filter.eq(AppField.appKey, request.getAppKey()));
        if (num == null) {
            num = 0L;
        }
        if (num > 0) {
            result.setCode(501);
            result.setMsg(String.format("标识%s已经使用过了", request.getAppKey()));
            return result;
        }

        return appApi.create(request);
    }

    @Override
    public ResponseObject<AppResponse> update(AppRequest request) {
        ResponseObject<AppResponse> result = new ResponseObject<>();
        if (StringUtils.hasText(request.getAppKey())) {
            Long num = appApi.countData(
                    Filter.eq(AppField.appKey, request.getAppKey()),
                    Filter.ne("id", request.getId())
            );
            if (num == null) {
                num = 0L;
            }
            if (num > 0) {
                result.setCode(501);
                result.setMsg(String.format("标识%s已经使用过了", request.getAppKey()));
                return result;
            }
        }
        return appApi.update(request);
    }
}
